<template>
  <div>
    <h1 class="">手机登录</h1>

    <el-form
      ref="loginFormRef"
      :model="user"
      :rules="rules"
      class="w100"
      status-icon
      label-position="top"
    >
      <SmsvcodeForm
        v-model:mobilenumber="user.mobileNumber"
        v-model:smsvcode="user.smsvcode"
        @send="SendSmsVcode"
        ref="smsvcodeFormRef"
      ></SmsvcodeForm>
      <el-form-item>
        <div class="remember row w100 jcfe">
          <router-link :to="'/login'">账号密码登录</router-link>
          <!-- <a href="javascript:void(0)" @click="SMSLogin">短信验证登录</a> -->
        </div>
      </el-form-item>
      <el-form-item>
        <el-button class="w100" type="primary" @click="onSmsLogin">
          {{ $t('登录') }}
        </el-button>
      </el-form-item>
    </el-form>

    <div class="forget-password row jcc">
      <router-link :to="'/login/registration'">立即注册</router-link>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { shios } from '@/api/Shios';
import { checkMobileNumber } from '@/libs/CheckFields';
import router from '@/route';
import { store } from '@/store';
import { ElMessage, FormInstance } from 'element-plus';
import { ref } from 'vue';

const user = ref({ mobileNumber: '', smsvcode: '' });

const rules = {
  mobileNumber: [
    {
      validator: checkMobileNumber,
      trigger: 'blur',
    },
  ],
  smsvcode: [
    { required: true, message: '请输入短信验证码', trigger: 'blur' },
    {
      max: 6,
      message: '长度错误',
      trigger: 'blur',
    },
  ],
};
const loginFormRef = ref<FormInstance>();
const smsvcodeFormRef = ref<FormInstance>();

/**
 * 发送登录短信验证码
 */
async function SendSmsVcode() {
  if (!smsvcodeFormRef.value) return;
  await smsvcodeFormRef.value.validateField('mobileNumber');

  var res = await shios.post<SendStatus>('/Sms/SendLoginSMSVerificationCode', {
    search: { mobileNumber: user.value.mobileNumber },
  });
  if (res.data?.code == 'Ok') {
    ElMessage.success('发送成功');
  } else {
    if (res.data?.message) {
      ElMessage.error(res.data.message);
    }
  }
}
/**
 * 点击登录
 */
async function onSmsLogin() {
  if (!smsvcodeFormRef.value) return;
  await smsvcodeFormRef.value.validate();

  const res = await shios.post<LoginDTO>('login/UseSMS', {
    data: user.value,
  });

  if (!res.ok) {
    return;
  }
  store.token.update(res.data.token);
  store.user.update(res.data.user);
  shios.token = store.token.state.accessToken;

  router.push('/welcome');
  //swipeVerifyDialogVisible.value = true;
}
</script>

<style lang="scss" scoped></style>
